#include "symbolTable.h"
#include <stdlib.h>
#include <time.h>
#include "context.h"

using namespace wolv::condition;

SymbolTable::SymbolTable()
{
	ResetContext();
}


SymbolTable::~SymbolTable()
{

}

VariableValue SymbolTable::GetSymbol( const std::string& name)
{
	std::string np = "";
	std::string varname = "";
	size_t pos = name.find('.');
	if (pos != std::string::npos)
	{
		np = name.substr(0, pos);
		varname = name.substr(pos+1);
	}
	else
	{
		np = name;
		varname = name;
	}


	if (table_.find(np) == table_.end())
	{
		return VariableValue();
	}
	return table_[np]->Access(varname, pContext_);
}

int SymbolTable::LinkImporter( const std::string& name, SymbolImporter* pImporter)
{
	table_[name] = pImporter;
	return 0;
}

int wolv::condition::SymbolTable::ResetImporter()
{
	table_.clear();
	return 0;
}

int SymbolTable::SetContext( LocalContext* pContext )
{
	pContext_ = pContext;
	return 0;
}

int SymbolTable::ResetContext()
{
	pContext_ = 0;
	return 0;
}



SymbolImporter::SymbolImporter( const std::string& _namespace )
:namepsace_(_namespace)
{

}

SymbolImporter::~SymbolImporter()
{

}

int SymbolImporter::Import( SymbolTable* symbolTabel )
{	
	symbolTabel->LinkImporter(namepsace_, this);

	return 0;
}


wolv::condition::VariableValue wolv::condition::SymbolImporter::Access( const std::string& name, LocalContext* pContext)
{
	return _access(name, pContext);
}


SystemImporter::SystemImporter()
:SymbolImporter("System")
{

}


wolv::condition::VariableValue wolv::condition::SystemImporter::_access( const std::string& name, LocalContext* pContext)
{
	if (name.find("Random_100") == 0)
	{
		int seed = 0;
		for (size_t i = 0; i != name.size(); ++i)
		{
			seed += name[i];
		}
		
		srand(pContext->GetStartTime() + seed);
		return (rand() % 100);
	}


	if (name == "Time")
	{
		return (int)pContext->GetStartTime();
	}

	if (name == "Hour")
	{
		tm stTime;
		time_t startTime = pContext->GetStartTime();
		localtime_r(&startTime, &stTime);

		return stTime.tm_hour;
	}

	if (name == "Minute")
	{
		tm stTime;
		time_t startTime = pContext->GetStartTime();
		localtime_r(&startTime, &stTime);

		return stTime.tm_hour * 60 + stTime.tm_min;
	}

	return VariableValue();
}


